using System;
using System.Text.RegularExpressions;
using LiteTools.domains.db;
using Sunny.UI;

namespace LiteTools.forms
{
    public partial class TagModelViewer : UIForm
    {
        public TagModelViewer()
        {
            InitializeComponent();
            ShowFamilys();
            tag_type_box.SelectedIndex = 0;
        }

        private void ShowFamilys()
        {
            var tlvTagFamilies = TlvTagFamilyHelper.GetTlvTagFamily();
            if (tlvTagFamilies != null && tlvTagFamilies.Count > 0)
            {
                tag_family_box.Clear();
            }
            else
            {
                UIMessageTip.ShowError(this, "当前还没有任何族，请先维护族信息，至少存在一个族方可操作！", 1500, true);
                return;
            }

            foreach (var tlvTagFamily in tlvTagFamilies)
            {
                tag_family_box.Items.Add(tlvTagFamily);
            }

            tag_family_box.DisplayMember = "ttf_name";
            tag_family_box.SelectedIndex = 0;
        }

        private void confirm_Click(object sender, EventArgs e)
        {
            if (!CheckValues())
            {
                return;
            }

            var selectedItem = tag_family_box.SelectedItem;
            var tagInfo = new TagInfoHelper.TagInfo
            {
                tag_family = ((TlvTagFamilyHelper.TlvTagFamily)selectedItem).ttf_id,
                tag_value = tag_value_text.Text,
                tag_desc = tag_desc_text.Text.Replace(" ","").Trim(),
                tag_type = tag_type_box.SelectedIndex.ToString()
            };
            var addTagInfo = TagInfoHelper.AddTagInfo(tagInfo);
            if (addTagInfo)
            {
                UIMessageTip.ShowOk(tag_desc_text, "添加成功！", 1000, true);
            }
            else
            {
                UIMessageTip.ShowError(tag_desc_text, "添加失败！", 1000, true);
            }
            Close();
        }

        private bool CheckValues()
        {
            // 最多允许四个字节
            var regex = new Regex("([0-9a-fA-F]{2}){0,4}");
            var tagValue = tag_desc_text.Text.Replace(" ","").Trim();
            if (regex.IsMatch(tagValue)) return true;
            UIMessageTip.ShowError(this, "Tag的值长度要求必须是2、4、6、8，且必须是一个合法的十六进制数！", 1500, true);
            return false;

        }

        private void cancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}